/**
 * Created by cjd on 2016/6/24.
 */
angular.module("app").controller("topic.info.Ctrl", ["$scope", "$http", "$stateParams", "topic","$timeout", function ($scope, $http, $stateParams, topic,$timeout) {
    if ($stateParams.id) {
        topic.getInfo({}, {id: $stateParams.id}, function (data) {
            if (data.statusCode == 0) {
                $scope.topicInfo = data.data;
                try{
                    $scope.topicInfo.intro = JSON.parse($scope.topicInfo.intro);
                }
                catch (e){
                    $scope.topicInfo.intro = [];
                }
            } else {
                alert(data.statusMessage)
            }
        })
    }
    else {
        $scope.topicInfo = {top: 1};
    }
    $scope.addIntroItem = function () {
        if (!$scope.topicInfo.intro) {
            $scope.topicInfo.intro = [];
        }
        var item = {type: "text", sort: $scope.topicInfo.intro.length || 0};
        $scope.topicInfo.intro.push(item);
    };
    $scope.removeIntroItem = function (currItem) {
        if (confirm("确定执行该操作吗?")) {
            $scope.topicInfo.intro.forEach(function (item, index) {
                if (currItem.sort == item.sort) {
                    $scope.topicInfo.intro.splice(index, 1)
                }
            })
        }
    };
    $scope.saveTopicInfo = function () {
        var tmp = angular.copy($scope.topicInfo);
        tmp.intro = JSON.stringify(tmp.intro);
        topic.saveInfo({}, tmp, function (data) {
            if (data.statusCode == 0) {
                alert("保存成功");
                $scope.goBack();
            } else {
                alert(data.statusMessage)
            }
        })
    }
    $scope.uploadPhoto = function(file,item){
        var form = new FormData();
        form.append("file", file);
        form.append("key", new Date().getTime() + /\.[^\.]+$/.exec(file.name)[0]);
        form.append("token", $scope.$parent.qiniuToken);
        var xhr = new XMLHttpRequest();
        xhr.open("POST", "http://upload.qiniu.com/", true);
        function callback() {
            if (xhr.readyState == 4) {
                $timeout(function() {
                    var data = angular.fromJson(xhr.responseText);
                    if (data.key) {
                        item.background = "http://img.dakaqi.cn/" + data.key;
                    } else if (data.code) {
                        alert(data.error);
                        return;
                    }
                }, 3000);
            }
        }
        xhr.onreadystatechange = callback;
        xhr.send(form);
    }
}]);